//
//  CardStyleLabel.swift
//  Game
//
//  Created by woniu on 2025/9/5.
//

import Foundation
import UIKit
import UIKit

class CardStyleLabel: UILabel {
    
    // 内边距属性
    private var contentEdgeInsets: UIEdgeInsets = .zero
    
    // 设置内边距的方法
    func setPadding(_ insets: UIEdgeInsets) {
        contentEdgeInsets = insets
        invalidateIntrinsicContentSize() // 刷新布局
    }
    
    // 初始化方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupCardStyle()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupCardStyle()
    }
    
    // 设置卡片样式
    private func setupCardStyle() {
        // 设置随机背景色
        backgroundColor = UIColor(
            hue: CGFloat.random(in: 0...1),
            saturation: CGFloat.random(in: 0.4...0.6),
            brightness: CGFloat.random(in: 0.9...1.0),
            alpha: 0.30
        )
        
        // 设置文字颜色（确保与背景色对比度足够）
        textColor = .white
        shadowColor = .black
        shadowOffset = CGSize(width: 0.5, height: 0.5)
        
        // 设置字体和文字对齐方式
        font = UIFont.systemFont(ofSize: 16, weight: .medium)
        textAlignment = .center
        
        // 卡片圆角
        layer.cornerRadius = 12
        clipsToBounds = true
        
        // 卡片阴影（需要关闭clipsToBounds才能显示阴影）
        clipsToBounds = false
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 0.15
        layer.shadowOffset = CGSize(width: 0, height: 2)
        layer.shadowRadius = 4
        
        // 内边距（上下左右各16点）
        let padding = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
        setPadding(padding)
    }
    
    // 重写绘制文本的方法，应用内边距
    override func drawText(in rect: CGRect) {
        super.drawText(in: rect.inset(by: contentEdgeInsets))
    }
    
    // 重写 intrinsicContentSize，调整标签的 intrinsic 大小以适应内边距
    override var intrinsicContentSize: CGSize {
        let size = super.intrinsicContentSize
        return CGSize(
            width: size.width + contentEdgeInsets.left + contentEdgeInsets.right,
            height: size.height + contentEdgeInsets.top + contentEdgeInsets.bottom
        )
    }
    
    // 重写布局方法，确保布局变化时正确应用内边距
    override func layoutSubviews() {
        super.layoutSubviews()
        layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).cgPath
    }
}
